<template>
    <div>
        <el-breadcrumb separator="/" class="top-banner">
            <el-breadcrumb-item :to="{ path: '/communitySettingIndex' }" class="top-banner-color">校区设置</el-breadcrumb-item>
            <el-breadcrumb-item>新增校区</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="edu-main">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="edu-ruleForm" name="el-form">
                <el-form-item label="门店选择：" prop="shopId" required>
                    <el-select v-model="ruleForm.shopId"  placeholder="请选择门店" @change="findShopsListChange">
                        <el-option v-for="(item,index) in findShopsList" :key="index" :label="item.businessName" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="校区名称：" prop="schoolName" required>
                    <el-input v-model.trim="ruleForm.schoolName" placeholder="30个字以内" :maxlength="30"></el-input>
                </el-form-item>
                <el-form-item label="校区地址：" prop="schoolAddress" required>
                    <el-input v-model.trim="ruleForm.schoolAddress"></el-input>
                </el-form-item>
                <el-form-item label="校区电话：" prop="schoolPhone" required>
                    <el-input v-model="ruleForm.schoolPhone"></el-input>
                </el-form-item>
                <el-form-item label="咨询微信：" prop="consultingQq">
                    <el-input v-model="ruleForm.consultingQq"></el-input>
                </el-form-item>
                <el-form-item label="LOGO(ERP端)：" prop="schoolLogo">
                    <gt-material :img="ruleForm.schoolLogo" :tipTxtShow='tipTxtShow' @change="schoolLogoChange" :materialUrl="newMaterialUrl"></gt-material>
                </el-form-item>
                <!-- <el-form-item label="手机端banner：" required>
                    <el-button type="primary" @click="addBanner">添加banner图</el-button>
                    <label for="" class="tip-txt">图片尺寸建议为750 * 360 px</label>
                    <el-table :data="ruleForm.bannerList" style="width: 800px" class="bannerTab">
                        <el-table-column label="banner图片">
                            <template slot-scope="scope">
                                 <el-form-item :prop="'bannerList.'+ scope.$index  +'.imagePath'" :rules="[{ required: true, message: '请选择图片' }]" >
                                    <gt-material :img="scope.row.imagePath" :tipTxtShow='tipTxtShow2' :width="188 + 'px'" :height="90 + 'px'"  :path="newPath" :materialUrl="newMaterialUrl"
                                    @change="imagePathChange($event,scope.$index)" @deleteImg="imagePathDelete(scope.$index)"></gt-material>
                                    <el-input v-model="scope.row.imagePath" style="display:none"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        
                        <el-table-column label="操作" width="150px">
                            <template slot-scope="scope">
                                <el-button type="info" plain size="mini" v-if="scope.$index != 0" @click="deleteBanner(scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item> -->
                <el-form-item label="应用功能：">
                    <div>
                        <el-switch v-model="ruleForm.onHomework" :active-value="0" :inactive-value="1" active-text="作业管理"></el-switch>
                        <label for="" class="tip-txt">老师布置班级作业，学员在学员端查看作业详情</label>
                    </div>
                    <div>
                        <el-switch v-model="ruleForm.onComments" :active-value="0" :inactive-value="1" active-text="评语管理"></el-switch>
                        <label for="" class="tip-txt">老师对学员发布评语，学员对评语进行回复</label>
                    </div>
                    <div>
                        <el-switch v-model="ruleForm.onExam" :active-value="0" :inactive-value="1" active-text="考试管理"></el-switch>
                        <label for="" class="tip-txt">老师管理班级学员考试成绩，学员在学员端查看个人考试成绩</label>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"  @click="submitForm('ruleForm')" :loading="submitLoading">保 存</el-button>
                    <!-- <el-button @click="resetForm('ruleForm')">返 回</el-button> -->
                    <el-button @click="goback">返 回</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import common from '@/assets/js/common'
import gtMaterial from '@/components/material.vue'
export default {
  data(){
      var validatePhone =(rule, value, callback)=>{
        var isPhone = /^((\+?86)|(\(\+86\)))?(13[0123456789][0-9]{8}|15[0123456789][0-9]{8}|17[0123456789][0-9]{8}|18[0123456789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
        var isfixed =/^0\d{2,3}-\d{7,8}(-\d{1,6})?$/;
        if((isPhone.test(value) || (isfixed.test(value)))){
            callback()
        }else{
            return callback(new Error('请输入正确的手机号或者电话号码'));
        }
      }
      return{
          logoimg:'',
          bannerFlag:false,
          findShopsList:[],
          ruleForm:{
            shopId:'',
            schoolName:'',
            schoolAddress:'',
            schoolPhone:'',
            consultingQq:'',
            schoolLogo:'',
            banners:'',
            schoolId:'',
            onHomework:0,
            onExam:0,
            onComments:0,
            bannerList:[{
                imagePath:'',
                imageUrl: '',
                id:''
            }],
          },
          rules:{
              shopId:[
                  {required: true, message: '请选择门店'}
              ],
              schoolName:[
                  {required: true, message: '请填写校区名称'}
              ],
              schoolAddress:[
                   { required: true, message: '请填写校区地址'}
              ],
              schoolPhone:[
                { required: true, message: '请填写校区电话'},
                { validator: validatePhone}
              ]
          },
          tipTxtShow:true,
          tipTxtShow2:false,
          errorTip:[],
          newMaterialUrl:'',
          schoolId:'',
          submitLoading: false,
          newPath:''         
      }
  },
  components:{
        gtMaterial,
    },
    
    methods: {
        loadData(){
            let that= this
            common.ajax({
                'url': eduAPI.activeAPI.findSchool,
                'type': "GET",
                'data':{
                    schoolId:that.schoolId
                },
                'success': function(data) {
                    console.log(data,'详情')
                    if (data.data) {
                        that.ruleForm = data.data
                        if(data.data.schoolLogo){
                            that.ruleForm.schoolLogo = that.newPath + that.ruleForm.schoolLogo
                        }
                        that.ruleForm.shopId = data.data.shopId;
                    }
                }
            })
        },
        //选择门店改变事件
        findShopsListChange(value){
            console.log(value)
            this.ruleForm.shopId = value
        },
        //logo改变事件
        schoolLogoChange(val){
            this.ruleForm.schoolLogo = val
            console.log(this.ruleForm.schoolLogo)
        },
        //banner 增加 删除
        addBanner(){
            let that = this
            let arr = {
                imagePath:'',
                imageUrl: '',
                id:''
            };
            that.ruleForm.bannerList.push(common.copy(arr))
        },
        deleteBanner(index){
            let that = this;
            let id;
            if(!that.ruleForm.bannerList[index].id){
                id = ''
            }else{
                id = that.ruleForm.bannerList[index].id
            }
            common.ajax({
                'url':eduAPI.activeAPI.delBanner,
                'type': "POST",
                'data':{
                    id: id,
                    schoolId: that.schoolId
                },
                'success': function(data) {
                    console.log(data);
                    that.ruleForm.bannerList.splice(index,1)
                    console.log(that.ruleForm.bannerList)
                },
            })
        },
        
        imagePathChange(val,index){
            this.ruleForm.bannerList[index].imagePath = val
        },
        imagePathDelete(index){
            this.ruleForm.bannerList[index].imagePath = ''
        },
        yanzheng(){
           
           // let patter = /^(http:\/\/duofriend.com\/)/;
            let patter = /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/ ;
            let that = this;
            that.ruleForm.bannerList.forEach((item,index)=>{
                if(!(patter.test(item.imagePath))){
                    that.bannerFlag = false
                    that.$set(that.errorTip,index,'链接只能使用http://duofriend.com/作前缀的地址')
                }else{
                    that.bannerFlag = true
                    that.$set(that.errorTip,index,'')
                }
            })
        },
        //清除banner验证
        clearError(index){
            this.$set(this.errorTip,index,'')
        },

        //save保存
        submitForm(formName) {
            let that = this
            that.$refs[formName].validate((valid) => {
                if (valid) {
                    that.submitLoading = true
                    if(!that.ruleForm.banners){
                        that.ruleForm.banners = ''
                    }
                    let bannerImg=[];
                     that.ruleForm.bannerList.forEach(function(key){  
                        let obj={
                            imagePath:key.imagePath.split("/upload")[1],
                            imageUrl:key.imageUrl,
                                id:key.id
                        }
                        bannerImg.push(obj)
                       })

                    let dataLog= that.ruleForm.schoolLogo;
                    dataLog = dataLog.split("/upload")[1];
                    bannerImg = JSON.stringify(bannerImg);
                    if(that.schoolId==0){that.schoolId=""}
                    let sendData={
                        shopId:that.ruleForm.shopId,
                        schoolName:that.ruleForm.schoolName,
                        schoolAddress:that.ruleForm.schoolAddress,
                        schoolPhone:that.ruleForm.schoolPhone,
                        consultingQq:that.ruleForm.consultingQq,
                        schoolLogo:dataLog,
                        // banners:bannerImg,
                        banners:"",
                        id:that.schoolId,
                        onHomework:0,
                        onExam:0,
                        onComments:0,
                      }
                    common.ajax({
                        'url': eduAPI.activeAPI.saveSchool,
                        'type': "POST",
                        'data':sendData,
                        'success': function(data) {
                            that.$message({
                                showClose: true,
                                message: '保存成功',
                                type: 'success'
                            });
                            that.submitLoading = false
                            that.$router.push({
                                name: "communitySettingIndex"
                            });
                        },
                        'warning':function(data){
                            that.$message({
                                showClose: true,
                                message: data.msg,
                                type: 'warning'
                            });
                            that.submitLoading = false
                        },
                        'error':function(data){
                            that.$message({
                                showClose: true,
                                message: data.msg,
                                type: 'warning'
                            });
                            that.submitLoading = false
                        }
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        //取消
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.errorTip = []
        },

        //返回
        goback(){
            this.$router.push({name:"communitySettingIndex"})
        }
    },
    mounted(){
        var that = this
        that.schoolId = parseInt(this.$route.params.schoolId)
        console.log(that.schoolId)
        //查询门店
        common.ajax({
            'url': eduAPI.activeAPI.findShops,
            'type': "GET",
            'success': function(data) {
                console.log(data,'门店');
                if (data.data) {
                    that.findShopsList = data.data;
                    if(that.schoolId == 0){
                        that.ruleForm.shopId = that.findShopsList[0].id
                    }
                }
                //详情
                that.loadData()
            }
        }); 

        //素材库和域名调用接口
        common.ajax({
            'url': eduAPI.activeAPI.getMaterialUrl,
            'type': "GET",
            'success': function(data) {
                console.log(data,'素材库和域名调用接口')
                if(data.data){
                    that.newMaterialUrl = data.data.materialImageHome
                    that.newPath = data.data.materialImageUrl
                }
            }
        })
    }
}
</script>
